package com.epfresh.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.epfresh.R;
import com.epfresh.activity.CenterListActivity;
import com.epfresh.activity.DcStoreActivity;
import com.epfresh.activity.HomeActivity;
import com.epfresh.activity.LoginActivity;
import com.epfresh.adapter.ViewBinderAreaCenter;
import com.epfresh.adapter.*;
import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.basedialog.CustomDialog;
import com.epfresh.bean.MarketBean;
import com.epfresh.bean.StoreDetail;
import com.epfresh.bean.TypeBean;
import com.epfresh.global.BaseFragment;
import com.epfresh.global.DataManager;
import com.epfresh.views.MultiStateView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;

public class MarketHomeFragmentRecycler extends BaseFragment {
    ArrayList<TypeBean> list = new ArrayList<>();
    ArrayList<TypeBean> topList = new ArrayList<>();
    ArrayList<TypeBean> bottomList = new ArrayList<>();



    View llBottom;
    GridView gvBottom;
    ImageView ivBottom;


    String marketId;

    private MultiStateView msView;

    MultiTypeAdapter multiAdapter;
    GridLayoutManager layoutManager;
    private List<Object> items = new ArrayList<>();
    private RecyclerView lvMarket;

    //Map<Integer,Integer> scrollPositionMap = new HashMap();

    public void setMarketId(String marketId) {
        this.marketId = marketId;
    }
    void firstLoad(){
        if (!firstSuccessFlag) {
            requestDialogFlag = true;
            refresh();
        }
    }

    int topPosition;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_market_home_recycler, container, false);
    }
    Animation inAnim;
    Animation outAnim;
    Animation topAnim;
    Animation bottomAnim;
    //GridView topGridView;
    RecyclerView.SmoothScroller smoothScroller;
    ViewBinderMarketChildCategory binderMarketChildCategory;
    ViewBinderMarketTopCategory binderMarketTopCategory;
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        ptrFrameLayout = (PtrMdFrameLayout) view.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);

        ivBottom = (ImageView)view.findViewById(R.id.iv_bottom);
        llBottom = view.findViewById(R.id.ll_bottom);
        gvBottom = (GridView)view.findViewById(R.id.gv_bottom);
        ivBottom.setOnClickListener(this);
        lvMarket = (RecyclerView) view.findViewById(R.id.lv_market);
        multiAdapter = new MultiTypeAdapter();

        ViewBinderAreaCenter viewBinderCenter = new ViewBinderAreaCenter();
        viewBinderCenter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if (data != null) {
                    clickCenter((MarketBean.StoresBeanX) data);
                }
            }
        });
        ViewBinderAreaTopGrid viewBinderTopGrid = new ViewBinderAreaTopGrid();

        multiAdapter.register(MarketBean.StoresBeanX.class, viewBinderCenter);//绑定的批发市场
        multiAdapter.register(MarketBean.MarketAreasBean.class, new ViewBinderAreaMarket());//某个区
        multiAdapter.register(String.class, new ViewBinderAreaTopTitle());//逛市场
        multiAdapter.register(Integer.class, new ViewBinderAreaBottom());//逛完了
        if(binderMarketTopCategory==null)
            binderMarketTopCategory = new ViewBinderMarketTopCategory();
        binderMarketTopCategory.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if (data != null) {
                    if(topPosition == ((MarketBean)items.get(0)).getTopCategories().indexOf(data))
                        return;
                    topPosition = ((MarketBean)items.get(0)).getTopCategories().indexOf(data);
                    items.remove(1);
                    items.add(1,((MarketBean) items.get(0)).getTopCategories().get(topPosition).getChildren());
                    multiAdapter.notifyItemChanged(1);
                }
            }
        });
        multiAdapter.register(MarketBean.class, binderMarketTopCategory);
        if(binderMarketChildCategory == null)
            binderMarketChildCategory = new ViewBinderMarketChildCategory();
        binderMarketChildCategory.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
/*                if (data != null) {
                    int childPosition = ((MarketBean)items.get(0)).getTopCategories().get(topPosition).getItem().indexOf(data);
                    T.toast("click child category"+childPosition); marketId topId childId
                }*/


                FragmentActivity activity = getActivity();
                if (activity != null && activity instanceof HomeActivity){

                    MarketBean.TopCateGory topCateGory = ((MarketBean) items.get(0)).getTopCategories().get(topPosition);


                    String topCategoryId =  topCateGory.getId();
                    String categoryId = topCateGory.getChildren().get(position).getCategoryId();
                    String nameId = topCateGory.getChildren().get(position).getId();
                    ((HomeActivity) activity).updateCategoryStatus(marketId,topCategoryId,categoryId,nameId);
                }

            }
        });
        multiAdapter.register(List.class, binderMarketChildCategory);


        layoutManager = new GridLayoutManager(getContext(), 4);

        smoothScroller = new LinearSmoothScroller(getContext()) {
            @Override protected int getVerticalSnapPreference() {
                return LinearSmoothScroller.SNAP_TO_START;
            }
        };


        viewBinderTopGrid.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if(data instanceof MarketBean.MarketAreasBean){
                    smoothScroller.setTargetPosition(items.indexOf(data));
                    layoutManager.startSmoothScroll(smoothScroller);
                }
            }
        });
        multiAdapter.register(TypeBean.class, viewBinderTopGrid);

        GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object item = items.get(position);
                return (item instanceof TypeBean) ? 1 : 4;
            }
        };
        layoutManager.setSpanSizeLookup(spanSizeLookup);
        lvMarket.setLayoutManager(layoutManager);
        lvMarket.setAdapter(multiAdapter);
        multiAdapter.setItems(items);
        inAnim = AnimationUtils.loadAnimation(getContext(), R.anim.anim_right_push_in);
        outAnim = AnimationUtils.loadAnimation(getContext(), R.anim.anim_right_push_out);
        topAnim = AnimationUtils.loadAnimation(getContext(), R.anim.anim_bottom_in);
        bottomAnim = AnimationUtils.loadAnimation(getContext(), R.anim.anim_bottom_out);
        lvMarket.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int firstPosition = layoutManager.findFirstVisibleItemPosition();
                if(list!=null&&firstPosition>list.size()-1){
                    ivBottom.setVisibility(View.VISIBLE);
                }else{
                    ivBottom.setVisibility(View.INVISIBLE);
                }
            }
        });
        bottomDeparAdapter = new TopDepartAdapter(getActivity(), bottomList, R.layout.item_depart_text);
        msView = (MultiStateView) view.findViewById(R.id.ms_view);
        msView.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        msView.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_EMPTY);
        msView.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_ERROR);
        msView.setOnErrorClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refresh();
            }
        });
    }


    @Override
    public String getBaseTag() {
        return null;
    }

    TopDepartAdapter bottomDeparAdapter;
    @Override
    public void onClick(View v) {
        int position;
        switch (v.getId()){
            case R.id.tv_depart:  //item_key_status
                if(v.getTag(R.id.item_key_status) instanceof TypeBean) {
                    TypeBean bean = (TypeBean) v.getTag(R.id.item_key_status);
                    if(list.indexOf(bean)==-1){
                        smoothScroller.setTargetPosition(list.size());
                        layoutManager.startSmoothScroll(smoothScroller);
                        //layoutManager.scrollToPositionWithOffset(list.size(),0);
                    }else {
                        smoothScroller.setTargetPosition(items.indexOf(bean.getMarketAreasBean()));
                        layoutManager.startSmoothScroll(smoothScroller);
                       // layoutManager.scrollToPositionWithOffset(items.indexOf(bean.getMarketAreasBean()),0);
                    }
                    if(llBottom.getVisibility()==View.VISIBLE){
                        llBottom.startAnimation(bottomAnim);
                        llBottom.setVisibility(View.GONE);
                        ivBottom.setImageResource(R.mipmap.market_show);
                    }
                }
                break;
            case R.id.iv_bottom:
                if(llBottom.getVisibility()==View.VISIBLE){
                    llBottom.startAnimation(bottomAnim);
                    llBottom.setVisibility(View.GONE);
                    ivBottom.setImageResource(R.mipmap.market_show);
                }else{
                    llBottom.startAnimation(topAnim);
                    llBottom.setVisibility(View.VISIBLE);
                    ivBottom.setImageResource(R.mipmap.market_close);
                }
                break;
            case R.id.tv_map:
                T.toast("地图");
                break;
            case R.id.tv_more_center:
                Intent tv_more = new Intent(getContext(), CenterListActivity.class);
                startActivity(tv_more);
                break;
            default:
                break;
        }
    }
    class TopDepartAdapter extends CommonAdapter<TypeBean> {
        public TopDepartAdapter(Context context, ArrayList<TypeBean> runPacks, int a) {
            super(context, runPacks, a);
        }

        @Override
        public void convert(final ViewHolder holder, final TypeBean bean) {
            if(bean.getMarketAreasBean()==null){
                holder.setText(R.id.tv_depart, "配送中心");
            }else {
                holder.setText(R.id.tv_depart, bean.getMarketAreasBean().getName());
            }
            holder.getView(R.id.tv_depart).setTag(R.id.item_key_status,bean);
            holder.setOnClickListener(R.id.tv_depart, MarketHomeFragmentRecycler.this);
        }
    }

    @Override
    public void onResume(){
        super.onResume();
        firstLoad();
    }

    boolean requestDialogFlag  = true;
    boolean firstSuccessFlag = false;

    OnRequestListener<MarketBean> onStoreRequestListener = new OnRequestListener<MarketBean>() {
        @Override
        public MarketBean jsonToObj(String s) {
            return new Gson().fromJson(s, MarketBean.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            ptrFrameLayout.refreshComplete();
            msView.setViewState(MultiStateView.VIEW_STATE_ERROR);
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            ptrFrameLayout.refreshComplete();
            msView.setViewState(MultiStateView.VIEW_STATE_ERROR);
        }

        @Override
        public void onStart(Object o) {
            if(requestDialogFlag) {
                requestDialogFlag = false;
                msView.setViewState(MultiStateView.VIEW_STATE_LOADING);
            }
        }

        @Override
        public void onResponse(ResponseEntity<MarketBean> responseEntity, Object o) {
            ptrFrameLayout.refreshComplete();
            firstSuccessFlag = true;
            hideProgressDialog();
            topList.clear();
            bottomList.clear();
            list.clear();
            MarketBean responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                MarketBean marketBean = responseElement;
                TypeBean typeBean;
                if(marketBean.getStores()!=null){
                    for(int i=0;i<marketBean.getStores().size();i++){
                        typeBean = new TypeBean();
                        typeBean.setType(1);
                        typeBean.setStoresBeanX(marketBean.getStores().get(i));
                        if(i==0) {
                            typeBean.getStoresBeanX().setMoreFlag(true);
                        }
                        list.add(typeBean);
                    }
                    bottomList.add(new TypeBean());
                }
                if(marketBean.getMarketAreas()!=null){
                    for(int i=0;i<marketBean.getMarketAreas().size();i++){
                        typeBean = new TypeBean();
                        typeBean.setMarketAreasBean(marketBean.getMarketAreas().get(i));
                        typeBean.setType(2);
                        list.add(typeBean);
                        topList.add(typeBean);
                        bottomList.add(typeBean);
                    }
                }

                items.clear();

                if(marketBean.getTopCategories()!=null&&marketBean.getTopCategories().size()>0) {
                    items.add(marketBean);
                    items.add(marketBean.getTopCategories().get(0).getChildren());
                }
                items.add(new String());//title

                items.addAll(topList);//gridview

                for(int i=0;i<list.size();i++){
                    if(list.get(i).getType()==2) {
                        items.add(list.get(i).getMarketAreasBean());//市场

                    }
                    else if(list.get(i).getType()==1) {
                        items.add(list.get(i).getStoresBeanX());//配送中心
                    }
                }
                items.add(0);
                multiAdapter.setItems(items);
                multiAdapter.notifyDataSetChanged();
                gvBottom.setAdapter(bottomDeparAdapter);
                msView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            }
            else {
                T.toast("返回数据错误");
                msView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
            }
        }
    };

    public void requestInfo() {
        RequestEntityMap rm = new RequestEntityMap();
        rm.setCmd(AppPurchaseRouterConstant.cmd_store_market_load);
        rm.putParameter("id", marketId);
        //rm.putParameter("id", "3");
        RequestTag tag = new RequestTag();
        tag.tag = AppPurchaseRouterConstant.cmd_store_market_load;
        tag.type = RequestTag.TYPE_CURRENT;
        request(rm, tag, onStoreRequestListener);
    }


    void bindCenter(final MarketBean.StoresBeanX storesBeanX){/*您正在申请绑定“%@”\n 申请后需配送中心通过 \n\n如有疑问，可联系配送中心*/
        CustomDialog.Builder builder = new CustomDialog.Builder(getContext());
        //builder.setMessage("您正在申请绑定\"" + list.get(position).getStoresBeanX().getName() + "\",\n申请后需配送中心通过\n\n如有疑问，可联系配送中心");//设置显示的内容
        builder.setMessage("您正在申请绑定\"" + storesBeanX.getName() + "\"，\n是否继续？");//设置显示的内容

        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {//添加确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                mHttpSure(storesBeanX.getId());
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("联系配送中心", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                Intent call = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + storesBeanX.getPhone()));//调出来拨打页面；
                getContext().startActivity(call);
                //dialog.dismiss();
            }

        });
        builder.createCenterBind(R.layout.dialog_round_layout).show();
    }

    /** 绑定 */
    public void mHttpSure(final String id) {
        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_store_store_bind);
        Map<String, String> map = new HashMap<>();
        map.put("storeId", id);
        data.setParameters(map);
        request(data, AppPurchaseRouterConstant.cmd_store_store_bind, new OnRequestListener<StatusEntity>() {
            @Override
            public StatusEntity jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, StatusEntity.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                Toast.makeText(getContext(), "服务器开小差了……", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                T.toast((arg == null ? "" : arg + ""));
            }

            @Override
            public void onStart(Object tag) {
                showProgressDialog();
            }
            @Override
            public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
                hideProgressDialog();
                StatusEntity responseElement = response.getResponseElement();
                if (responseElement.isSuccess()) {
                    DataManager.getInstance().bindStoreReFresh = true;
                    T.toast("绑定中");
                    ((HomeActivity)getActivity()).reFreshStore();
                    refresh();
                }else {
                    T.toast("服务器出现小问题，请稍后再试");
                }
            }
        });
    }




    public void requestSingleDc(boolean isSilent, String id) {
        if (getActivity() != null) {
            RequestEntityMap re = new RequestEntityMap();
            re.putParameter("storeId", id);
            re.setCmd(AppPurchaseRouterConstant.cmd_store_store_dcStore);
            RequestTag requestTag = new RequestTag();
            requestTag.tag = AppPurchaseRouterConstant.cmd_store_store_dcStore;
            if (isSilent) {
                requestTag.type = RequestTag.TYPE_CURRENT;
                requestTag.arg1 = "silent";
                re.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
                ApplicationHelper.getInstance().requestSilent(re, requestTag, onDetailRequestListener2);
//                request(re, requestTag, onDetailRequestListener);
            } else {
                requestTag.arg1 = "1";
                request(re, requestTag, onDetailRequestListener2);
            }

        }
    }


    OnRequestListener<StoreDetail> onDetailRequestListener2 = new OnRequestListener<StoreDetail>() {
        @Override
        public StoreDetail jsonToObj(String s) {
            return new Gson().fromJson(s, StoreDetail.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            if (getActivity() != null) {
                if (o1 != null && o1 instanceof RequestTag) {
                    RequestTag tag = (RequestTag) o1;
                    if ("silent".equals(tag.arg1)) {
//                        storeDetail = null;
                    } else {
                        hideProgressDialog();
                    }
                } else {
                    hideProgressDialog();
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            if (getActivity() != null) {
                if (o1 != null && o1 instanceof RequestTag) {
                    RequestTag tag = (RequestTag) o1;
                    if ("silent".equals(tag.arg1)) {
//                        storeDetail = null;
                    } else {
                        hideProgressDialog();
                    }
                } else {
                    hideProgressDialog();
                }
            }
        }

        @Override
        public void onStart(Object o1) {
            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    showProgressDialog();
                }
            } else {
                showProgressDialog();
            }

        }

        @Override
        public void onResponse(ResponseEntity<StoreDetail> responseEntity, Object o1) {
            if (getActivity() != null) {
                StoreDetail responseElement = responseEntity.getResponseElement();
                if (responseElement != null) {
//                    storeDetail = responseElement;
                }
                if (o1 != null && o1 instanceof RequestTag) {
                    RequestTag tag = (RequestTag) o1;
                    if ("silent".equals(tag.arg1)) {

                    } else {
                        hideProgressDialog();
                        intoDcPage(responseElement);
                    }
                } else {
                    hideProgressDialog();
                    intoDcPage(responseElement);
                }

            }
        }
    };


    public void intoDcPage(StoreDetail responseElement) {
        if (responseElement != null && getActivity() != null) {

            if (!responseElement.isResult()) {
                Intent tv_more = new Intent(getActivity(), CenterListActivity.class);
                startActivity(tv_more);
            } else {
                Intent tv_bulk_load = new Intent(getActivity(), DcStoreActivity.class);
                tv_bulk_load.putExtra("data", new Gson().toJson(responseElement));
                startActivity(tv_bulk_load);
            }
        }
    }

    private PtrMdFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvMarket, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            if(binderMarketChildCategory!=null)
                binderMarketChildCategory.scrollLeft();
            if(binderMarketTopCategory!=null)
                binderMarketTopCategory.scrollLeft();
            refresh();
        }
    };

    public void refresh() {
        if (getActivity() != null) {
            topPosition = 0;
            requestInfo();
        }
    }

    void clickCenter(MarketBean.StoresBeanX storesBeanX){
        if(ApplicationHelper.getInstance().getUser().getAccess_token()==null){
            firstSuccessFlag = false;
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            intent.putExtra("home_tab_index", 0);
            startActivity(intent);
            return;
        }

        if("1".equals(storesBeanX.getBindingStatus())){
            bindCenter(storesBeanX);
        }else if("3".equals(storesBeanX.getBindingStatus())){
            requestSingleDc(false,storesBeanX.getId());
        }else{
            T.toast("正在审核");
            return;
        }
    }
}
